<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>设置组别</title>
    <link rel="stylesheet" href="../utils/bootstrap-5.3.3-dist/css/bootstrap.min.css">
    <script src="../utils/bootstrap-5.3.3-dist/js/bootstrap.min.js"></script>
    <link rel="stylesheet" href="../utils/icon/iconfont.css">
    <link rel="stylesheet" href="../css/shared.css">
    <style>
        /*中部布局*/
        .central-layout {
            display: grid;
            grid-template-rows: 70px 470px 50px;
            width: 80vw;
            margin: 0 auto;
        }

        /*弹窗中部布局*/
        .dialog-body-layout {
            display: grid;
            grid-template-columns: auto auto;
            padding: 5px;
        }

        .dialog-body-right {
            display: grid;
            grid-template-rows: auto auto;
        }
    </style>
</head>
<body>
<div class="body-grid">
    <!--头部-->
    <div class="header-grid">
        <!--    返回按钮-->
        <div>
            <button class="btn btn-secondary iconfont go-back-button" onclick="window.location.href='project.html';">
                &#xe623;
            </button>
        </div>
        <!--    标题-->
        <div class="page-title" id="page-title">
            <script>
                document.getElementById("page-title").innerText=window.sessionStorage.getItem("competitionName")
                +"--设置组别"
            </script>
        </div>
        <div></div>
    </div>
    <!--中部-->
    <div class="central-layout">
        <div>
            <button id="del-bh" class="btn btn-danger" style="float: left;margin-top: 15px;"
                    onclick="openDialog('del-batch-group-dialog')">
                批量删除
            </button>
            <button type="button" class="btn btn-primary"
                    style="float: right;margin-top: 15px;"
                    id="add-group-pop"
                    onclick="openGroupDialog()">
                设置组别
            </button>
            <!--            弹窗-->
            <div id="group-dialog" class="my-dialog" style="display: none">
                <div class="my-dialog-header">
                    <!--                    标题占位-->
                    <span>设置组别</span>
                    <button type="button" class="btn-close close-icon"
                            onclick="closeGroupDialog()"></button>
                </div>
                <div class="my-dialog-body dialog-body-layout">
                    <div>组别：</div>
                    <div class="dialog-body-right">
                        <div>
                            <label><input type="checkbox" name="groups" value="M10">M10</label>
                            <label><input type="checkbox" name="groups" value="M12">M12</label>
                            <label><input type="checkbox" name="groups" value="M14">M14</label>
                            <label><input type="checkbox" name="groups" value="M16">M16</label>
                            <label><input type="checkbox" name="groups" value="M19">M19</label>
                            <label><input type="checkbox" name="groups" value="M22">M22</label>
                            <label><input type="checkbox" name="groups" value="M35">M35</label>
                            <label><input type="checkbox" name="groups" value="M45">M45</label>
                            <label><input type="checkbox" name="groups" value="M55">M55</label>
                            <label><input type="checkbox" name="groups" value="M65">M65</label>

                            <label><input type="checkbox" name="groups" value="W10">W10</label>
                            <label><input type="checkbox" name="groups" value="W12">W12</label>
                            <label><input type="checkbox" name="groups" value="W14">W14</label>
                            <label><input type="checkbox" name="groups" value="W16">W16</label>
                            <label><input type="checkbox" name="groups" value="W19">W19</label>
                            <label><input type="checkbox" name="groups" value="W22">W22</label>
                            <label><input type="checkbox" name="groups" value="W35">W35</label>
                            <label><input type="checkbox" name="groups" value="W45">W45</label>
                            <label><input type="checkbox" name="groups" value="W55">W55</label>
                            <label><input type="checkbox" name="groups" value="W65">W65</label>
                            <label><input type="checkbox" name="groups" value="公开组">公开组</label>
                            <label><input type="checkbox" name="groups" value="DXM">DXM</label>
                            <label><input type="checkbox" name="groups" value="DXW">DXW</label>
							<label><input type="checkbox" name="groups" value="小学低年级组">小学低年级组</label>
							<label><input type="checkbox" name="groups" value="小学高年级组">小学高年级组</label>
							<label><input type="checkbox" name="groups" value="初中组">初中组</label>
							<label><input type="checkbox" name="groups" value="高中组">高中组</label>
							<label><input type="checkbox" name="groups" value="大学组">大学组</label>
                        </div>
                        <small style="color: red"></small>
                    </div>

                </div>

                <div class="my-dialog-footer">
                    <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                            onclick="closeGroupDialog()">取消
                    </button>
                    <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                            onclick="submitGroupDialog()">确认
                    </button>
                </div>
            </div>
        </div>
        <!--    表格-->
        <div class="table-responsive">
            <table id="group-table" class="table table-sm table-bordered text-center" style="width: 50%;margin: auto">
                <thead>
                <tr>
                    <th>
                        <label>
                            全选
                            <input type="checkbox" onclick="selectMul('group-table')">
                        </label>
                    </th>
                    <th>组别名称</th>
                    <th>操作</th>
                </tr>
                </thead>
                <tbody id="group-tbody" class="table-group-divider">
                </tbody>
            </table>
        </div>
        <div>
            <!--    分页组件-->
            <ul class="pagination page-ul-flex" id="pagination">
            </ul>
        </div>


    </div>
    <!--尾部-->
    <div class="footer-grid">
        <!--网格留空-->
        <div></div>
        <!--进度条-->
        <div id="progress-bar" class="progress-bar-flex">
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增赛事</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">新增项目</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">设置组别</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">导入选手</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">下发号码</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">制卡</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">签到</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">批次管理</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">规则设置</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">开始比赛</div>
                <i class="iconfont progress-bar-arrow">&#xe604;</i>
            </div>
            <div class="progress-bar-grid">
                <button type="button" class="btn btn-success progress-bar-button" disabled></button>
                <div class="progress-bar-text">成绩计算</div>
                <i class="iconfont progress-bar-arrow" style="visibility: hidden;">&#xe604;</i>
            </div>
        </div>
        <!--   下一步-->
        <div>
            <button class="btn btn-primary iconfont next-button" id="btn-progress"
                    onclick="nextProgress(ATHLETE_PROGRESS,'athlete.html')">&#xe65b;
            </button>
        </div>
    </div>
    <!--单个删除弹窗-->
    <div id="del-one-group-dialog" class="my-dialog my-dialog-smaller" style="display: none">
        <div class="my-dialog-header">
            <!--                    标题占位-->
            <span>确定要删除吗？</span>
            <button type="button" class="btn-close close-icon"
                    onclick="closeDialog('del-one-group-dialog')"></button>
        </div>
        <div class="my-dialog-body">
        </div>
        <div class="my-dialog-footer">
            <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                    onclick="closeDialog('del-one-group-dialog')">取消
            </button>
            <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                    onclick="deleteOneGroup('del-one-group-dialog')">确认
            </button>
        </div>
    </div>
    <!--批量删除弹窗-->
    <div id="del-batch-group-dialog" class="my-dialog my-dialog-smaller" style="display: none">
        <div class="my-dialog-header">
            <!--                    标题占位-->
            <span>确定要批量删除吗？</span>
            <button type="button" class="btn-close close-icon"
                    onclick="closeDialog('del-batch-group-dialog')"></button>
        </div>
        <div class="my-dialog-body">
        </div>
        <div class="my-dialog-footer">
            <button type="button" class="btn btn-secondary btn-sm my-dialog-ft-btn"
                    onclick="closeDialog('del-batch-group-dialog')">取消
            </button>
            <button type="button" class="btn btn-primary btn-sm my-dialog-ft-btn"
                    onclick="deleteBatchGroup('group-table','del-batch-group-dialog')">确认
            </button>
        </div>
    </div>
</div>
<script src="../js/pages.js"></script>
<script src="../api/urls.js"></script>
<script src="../js/dialog.js"></script>
<script src="../js/progress.js"></script>
<script>
    updateProgress("progress-bar", GROUP_PROGRESS);


    //页码
    let pageNum = 1;
    //一页多少条
    let pageSize = 20;
    //总条数
    let total;
    //总页数
    let pages;
    //请求记录
    let records;
    //删除id
    let delId;

    /**
     * 多选框实现
     */
    function selectMul(tableId) {
        let mulSelect = document.querySelector("#" + tableId + " thead input");
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            tr.firstElementChild.firstElementChild.checked = mulSelect.checked;
        }
    }

    /**
     * 打开新增弹窗
     */
    async function openGroupDialog() {
        let groups = document.querySelectorAll("input[name='groups']");
        for (let group of groups) {
            group.parentElement.removeAttribute("style");
        }
        let url = new URL(GROUP_URL + GET_URL);
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url).then(response => {
            return response.json();
        }).then(groupList => {
            for (let group of groups) {
                for (const groupListElement of groupList) {
                    if (groupListElement.name === group.value) {
                        group.parentElement.style.display = "none";
                        break;
                    }
                }
            }
        });
        openDialog('group-dialog');
    }

    /**
     * 关闭新增弹窗
     */
    function closeGroupDialog() {
        let groups = document.querySelectorAll("input[name='groups']");
        for (let group of groups) {
            group.checked = false;
        }
        let element = document.querySelector(".dialog-body-right>small");
        element.textContent = "";
        closeDialog("group-dialog");
    }

    /**
     * 提交弹窗
     */
    async function submitGroupDialog() {
        let groupsChecked = document.querySelectorAll("input[name='groups']:checked");
        if (!groupsChecked || groupsChecked.length === 0) {
            let element = document.querySelector(".dialog-body-right>small");
            element.textContent = "必须选择组别！";
            return;
        }
        let competitionId = window.sessionStorage.getItem("competitionId");
        let reqBody = [];
        for (let groupsCheckedElement of groupsChecked) {
            let group = {};
            group.name = groupsCheckedElement.value;
            group.competitionId = competitionId;
            reqBody.push(group);
        }
        await fetch(GROUP_URL + "/addBatch", {
            method: "POST",
            headers: new Headers({"Content-Type": "application/json"}),
            body: JSON.stringify(reqBody)
        });
        closeGroupDialog();
        await showPage();
    }

    /**
     * 判断是否有运动员
     */
    async function hasAthlete() {
        let url = new URL(ATHLETE_URL + "/hasOne");
        url.searchParams.set("competitionId", window.sessionStorage.getItem("competitionId"));
        await fetch(url).then(resp => {
            return resp.json();
        }).then(result => {
            if (result.hasOne) {
                let delBh = document.getElementById("del-bh");
                delBh.disabled=true;
                let dels = document.querySelectorAll("#group-tbody .btn-danger");
                document.getElementById("add-group-pop").disabled = true;
                for (let del of dels) {
                    del.disabled=true;
                }
            }
        })
    }

    /**
     * 渲染表格
     */

    function drawGroupTable(records) {
        let mulSelect = document.querySelector("#group-table thead input");
        mulSelect.checked = false;
        let tableBody = document.getElementById("group-tbody");
        tableBody.innerHTML = "";
        for (let record of records) {
            let trElement = document.createElement("tr");
            trElement.dataset.groupId = record.id;
            let tdElement1 = document.createElement("td");
            let inputElement = document.createElement("input");
            inputElement.type = "checkbox";
            tdElement1.append(inputElement);
            let tdElement2 = document.createElement("td");
            tdElement2.textContent = record.name;
            let tdElement6 = document.createElement("td");
            let buttonElement2 = document.createElement("button");
            buttonElement2.classList.add("btn", "btn-danger", "btn-sm", "iconfont");
            buttonElement2.textContent = "\u{e67c}删除";
            buttonElement2.addEventListener("click", () => {
                delId = record.id;
                openDialog("del-one-group-dialog");
            });
            tdElement6.append(buttonElement2);
            trElement.append(tdElement1, tdElement2, tdElement6);
            tableBody.append(trElement);
        }
    }

    /**
     * 批量删除
     */
    async function deleteBatchGroup(tableId, dialogId) {
        let deleteIds = [];
        let trs = document.querySelectorAll("#" + tableId + " tbody>tr");
        for (let tr of trs) {
            if (tr.firstElementChild.firstElementChild.checked) {
                deleteIds.push(Number(tr.dataset.groupId));
            }
        }
        closeDialog(dialogId);
        if (deleteIds.length !== 0) {
            await fetch(GROUP_URL + DELETE_BATCH_URL, {
                method: "POST",
                headers: new Headers({"Content-Type": "application/json"}),
                body: JSON.stringify(deleteIds)
            });
            await showPage();
        }
    }

    /**
     * 单个删除
     */
    async function deleteOneGroup(dialogId) {
        closeDialog(dialogId);
        let url = new URL(GROUP_URL + "/deleteById");
        url.searchParams.set("id", delId);
        await fetch(url, {method: "POST"});
        await showPage();
    }

    //实现分页的方法
    async function getPage(pageNum, pageSize) {
        let url = new URL(GROUP_URL + PAGE_URL);
        url.searchParams.set("pageNum", pageNum);
        url.searchParams.set("pageSize", pageSize);
        url.searchParams.set("competitionId",window.sessionStorage.getItem("competitionId"));
        await fetch(url).then(response => {
            console.log(response)
            if (response.ok && response.headers.get("Content-Type") === "application/json") {
                return response.json();
            } else {
                
                throw new Error(`未知相应状态 ${response.status}或Content-Type：${response.headers.get("Content-Type")}`);
            }
        }).then(pageInfo => {
            pages = pageInfo.pages;
            total = pageInfo.total;
            records = pageInfo.records;
            if(records.length>0){
                document.getElementById("btn-progress").disabled=false;
            }else{
                document.getElementById("btn-progress").disabled=true;
            }
            drawGroupTable(records);
        }).catch(error => {

                console.log("分页错误：", error);
        });
        await hasAthlete();
    }

    //上一页
    async function prePage() {
        pageNum = pageNum - 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    //下一页
    async function nextPage() {
        pageNum = pageNum + 1;
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages)
    }

    //点击切换
    async function handlePage(page) {
        if (page !== pageNum) {
            pageNum = page
            await getPage(pageNum, pageSize);
            createpage(pageNum, pageSize, total, pages);
        }

    }
    /**
     * 改变每页条数
     */
    async function changePageSize(value) {
        pageSize=Number(value);
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    // 创建分页组件
    async function showPage() {
        await getPage(pageNum, pageSize);
        createpage(pageNum, pageSize, total, pages);
    }

    (async () => {
        await showPage();
    })();

</script>
</body>
</html>